<template>

  <div>
    <!--搜索框-->
    <div class="search-box">
      <el-form :inline="true" :model="query" class="demo-form-inline" size="small">

        <el-form-item label="课程标题">
          <el-input v-model="query.title" placeholder="名字"></el-input>
        </el-form-item>

        <el-form-item label="课程状态">
          <el-select v-model="query.status" placeholder="课程状态">
            <el-option label="全部" value="all"></el-option>
            <el-option label="未发布" value="Draft"></el-option>
            <el-option label="已发布" value="Normal"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="query.startTime"
            type="date"
            placeholder="开始时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="query.endTime"
            type="date"
            placeholder="结束时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getList()">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="reLoad">清空</el-button>
        </el-form-item>

      </el-form>

    </div>
    <!--数据页-->
    <div class="data-box">
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
      >

        <el-table-column
          prop="title"
          label="课程标题"
          width="220">
        </el-table-column>

        <el-table-column
          label="封面图"
          width="180">
          <template slot-scope="scope"><img :src="scope.row.cover" alt="" class="img-box"
                                            @click="showAvatar(scope.row.cover)"></template>
        </el-table-column>

        <el-table-column
          label="课程状态"
          width="100">
          <template slot-scope="scope">
            {{scope.row.status === 'Draft' ? '未发布' : '已发布'}}
          </template>
        </el-table-column>

        <el-table-column
          prop="gmtCreate"
          label="创建时间"
          width="180">
        </el-table-column>

        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button v-if="scope.row.status === 'Draft'" type="success" size="mini"
                         @click="changeStatus(scope.row,'上架')">上架
              </el-button>
              <el-button v-if="scope.row.status === 'Normal'" type="info" size="mini"
                         @click="changeStatus(scope.row,'下架')">下架
              </el-button>
              <el-button type="primary" size="mini" @click="alterBaseInfo(scope.row.id)">修改基础信息</el-button>
              <el-button type="primary" size="mini" @click="showChapter(scope.row)">修改章节信息</el-button>
              <el-button type="danger" size="mini" @click="deleteCourse(scope.row.id,scope.row.title)">删除</el-button>
            </el-row>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <!--分页条-->
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper, ->"
        :page-size="pageSize"
        :total="total"
        :current-page="pageNum"
        @current-change="getList">
      </el-pagination>
    </div>
    <!--视频封面-->
    <el-dialog title="视频封面" :visible.sync="dialogAvatarVisible">
      <div class="teacher-avatar-box">
        <img :src="avatar" class="teacher-avatar">
      </div>
    </el-dialog>
    <!--修改章节信息-->
    <el-dialog title="章节信息" :visible.sync="dialogChapter">
      <div>
        <div>
          <el-button type="primary" @click="showDialogChild" size="small">添加</el-button>
          <el-button type="primary" @click="importChapter" size="small">批量导入</el-button>
          <el-button type="danger" @click="deleteAll" size="small">删除全部</el-button>
        </div>
        <div>
          <el-table
            :data="chapters"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column
              prop="sort"
              label="排序号"
              sortable
              width="120">
            </el-table-column>
            <el-table-column
              prop="title"
              label="章节名称"
              sortable
              width="180">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <div style="display: flex; justify-content: flex-end; width: 320px">
                  <el-button v-if="scope.row.pid == 0" type="success" size="mini" @click="saveChild(scope.row)">添加子级
                  </el-button>
                  <el-button v-if="!scope.row.videoId && scope.row.pid != 0" type="success" size="mini"
                             @click="uploadVideo(scope.row.id)">添加视频
                  </el-button>
                  <el-button v-if="scope.row.videoId" type="danger" size="mini" @click="deleteVideo(scope.row.id)">删除视频
                  </el-button>
                  <el-button v-if="scope.row.videoId" type="primary" size="mini">查看视频</el-button>
                  <el-button type="primary" size="mini" @click="updateOne(scope.row)">修改</el-button>
                  <el-button type="danger" size="mini" @click="deleteOne(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
    <!--添加章节-->
    <el-dialog :title="title" :visible.sync="dialogChild">
      <el-form :model="chapter">
        <el-form-item v-if="showTitle" :label="belong" :label-width="formLabelWidth">
          <el-input v-model="pname" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="章节名称" :label-width="formLabelWidth">
          <el-input v-model="chapter.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序号" :label-width="formLabelWidth"
                      prop="sort"
                      :rules="[
                                  { required: true, message: '排序号不能为空'},
                                  { type: 'number', message: '排序号必须为数字值'}
                                ]"
        >
          <el-input v-model.number="chapter.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="saveOne">确 定</el-button>
      </div>
    </el-dialog>
    <!--批量导入-->
    <el-dialog title="批量导入课程章节" :visible.sync="dialogFormVisible">
      <span>文件名称后出现绿色勾即代表导入完毕</span>
      <span class="a-class">
        <a href="https://alan-guli.oss-cn-shenzhen.aliyuncs.com/excel/chapter-import.xlsx">点击下载导入模板</a>
      </span>
      <el-upload
        class="upload-demo"
        :on-success="uploadChapterSuccess"
        :action="uploadUrl"
        multiple
        :limit="1">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </el-dialog>
    <!--添加视频-->
    <el-dialog title="上传视频" :visible.sync="dialogVideo">
      <el-upload
        class="upload-demo"
        action="http://127.0.0.1:8003/vod/video/upload"
        :on-change="handleChangeVideo"
        :on-success="uploadSuccess"
        :file-list="video.videos">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传一个视频文件</div>
      </el-upload>
    </el-dialog>
    <!--修改课程基础信息-->
    <el-dialog title="课程基础信息" :visible.sync="dialogBaseInfo">
      <div class="data">
        <div class="data-box">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="课程名称">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="课程讲师">
              <el-select v-model="form.teacherId" placeholder="请选择课程讲师">
                <el-option v-for="t in teachers" :label="t.name" :value="t.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程分类">
              <el-cascader :options="options" :show-all-levels="true" v-model="form.subjectIds"></el-cascader>
            </el-form-item>
            <el-form-item label="收费课程" :disabled="true">
              <el-radio-group v-model="form.toll">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课程价格"
                          prop="price"
                          :rules="[
                                  { type: 'number', message: '课程价格必须为数字值'}
                                ]">
              <el-input v-model.number="form.price" :disabled="!form.toll"></el-input>
            </el-form-item>
            <el-form-item label="课程封面">
              <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:8002/eduoss/fileoss"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="conver" :src="conver" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程状态" :disabled="true">
              <el-radio-group v-model="form.status">
                <el-radio label="Draft" :disabled="true">未发布</el-radio>
                <el-radio label="Normal" :disabled="true">已发布</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课时"
                          prop="lessonNum"
                          :rules="[
                                  { type: 'number', message: '课时必须为数字值'}
                                ]">
              <el-input type="input" v-model.number="form.lessonNum"></el-input>
            </el-form-item>
            <el-form-item label="课程简介">
              <tinymce :height="300" v-model="form.description"/>
            </el-form-item>
          </el-form>
        </div>
        <div class="btn-box">
          <el-button type="primary" @click="saveCourse" size="small">保存信息</el-button>
        </div>
      </div>
    </el-dialog>

  </div>

</template>

<style>

  .avatar {
    width: 600px;
    height: 460px;
    display: block;
  }


  .img-box {
    width: 60px;
    height: 46px;
  }

  .pagination {
    float: right;
    margin-right: 5px;
  }

  .data-box {
    margin: 0 15px 15px 15px;
    border: #f4f4f5 1px solid;
  }

  .search-box {
    border: #f4f4f5 1px solid;
    margin: 15px 15px 5px 15px;
    padding: 10px 0 0 5px;
  }

  .a-class {
    display: block;
    margin: 20px 0;
    color: #409EFF;
  }

  .teacher-avatar-box {
    margin: auto;
  }

  .teacher-avatar {
    display: block;
    margin: auto;
    width: 90%;
    height: 90%;
  }

  .btn-box {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }


  .tinymce-container {
    line-height: 29px;
  }

</style>

<script>
  import teacher from "@/api/edu/teacher";
  import subject from "@/api/edu/subject";
  import chapter from "@/api/edu/chapter";
  import course from "@/api/edu/course";
  import Tinymce from '@/components/Tinymce';

  export default {
    components: {Tinymce},
    data() {
      return {

        // 分页参数
        tableData: [],
        pageSize: 6,
        pageNum: 1,
        query: {
          startTime: '',
          endTime: '',
          status: "all"
        },
        total: 0,

        // 视频封面
        dialogAvatarVisible: false,
        avatar: '',

        // 修改章节信息
        dialogChapter: false,
        chapters: [],
        pname: '',
        belong: '',
        chapter: {},
        title: 'title',
        showTitle: true,
        dialogChild: false,
        formLabelWidth: '100px',
        course: {},
        courseId: '',

        // 批量导入章节内容
        dialogFormVisible: false,
        uploadUrl: '',

        // 视频上传
        dialogVideo: false,
        video: {videos: []},

        // 课程基础信息
        form: {
          status: 'Draft',
          toll: true,
          cover: '',
          teacherId: '',
          subjectIds: []
        },
        conver: '',

        // 下拉框的值
        teachers: [],
        options: [],
        dialogBaseInfo: false

      }
    },
    created() {
      this.getList()
    },
    methods: {
      // 01 分页查询
      getList(page = 1) {
        this.pageNum = page
        this.query.pageSize = this.pageSize
        this.query.pageNum = this.pageNum
        course
          .page(this.query)
          .then(response => {
            this.tableData = response.data.list
            this.total = response.data.total
          })
          .catch(error => console.log(error));
      },

      // 02 删除课程
      deleteCourse(id, title) {
        this.$confirm('确定删除课程 - ' + title + '  ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          course.deleteCourse(id).then(response => {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 03 查看封面详情
      showAvatar(url) {
        this.avatar = url
        this.dialogAvatarVisible = true;
      },

      // 04 清空条件查询
      reLoad() {
        this.query = {
          pageSize: this.pageSize,
          pageNum: this.pageNum
        }
        this.getList();
      },

      // 05 上,下架视频
      changeStatus(row, operating) {
        this.$confirm('确定' + operating + '课程 - ' + row.title + '  ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          course.changeStatus(row.id).then(response => {
            this.getList()
            this.$message({
              type: 'success',
              message: operating + '成功!',
            });
          })
        })
      },

      // 06 打开章节对话框
      showChapter(row) {
        this.course = {...row};
        this.courseId = row.id;
        chapter.getAll(row.id).then(response => {
          this.chapters = response.data.list;
          this.dialogChapter = true;
        })
      },

      // 11 打开对话框
      showDialogChild() {
        this.belong = '所属课程';
        this.title = "添加章节";
        this.pname = this.course.title;
        this.chapter = {};
        this.showTitle = true;
        this.dialogChild = true;
        this.chapter.id = ''
      },

      // 12 关闭对话框
      cancelDialog() {
        this.dialogChild = false;
        this.chapter.id = ''
      },

      // 06 删除全部章节
      deleteAll() {
        this.$confirm('确定删除课程 - ' + this.pname + ' 全部章节 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          chapter.deleteAll(this.courseId).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
            this.getChapterList();
          })
        })
      },

      // 05 添加一个课程章节
      saveOne() {
        if (this.chapter.id) {
          this.chapter.courseId = this.courseId;
          chapter.updateOne(this.chapter).then(response => {
            this.dialogChild = false;
            this.chapter = {};
            this.getChapterList()
          })
        } else {
          this.chapter.courseId = this.courseId;
          chapter.saveOne(this.chapter).then(response => {
            this.dialogChild = false;
            this.chapter = {};
            this.getChapterList()
          })
        }
      },

      // 获取所有的章节信息
      getChapterList() {
        if (this.courseId != -1) {
          chapter.getAll(this.courseId).then(response => {
            this.chapters = response.data.list;
          })
        }
      },

      // 09 添加子级
      saveChild(row) {
        this.title = "添加子级";
        this.chapter = {};
        this.showTitle = true;
        this.chapter.pid = row.id;
        this.belong = '所属章节';
        this.pname = row.title;
        this.chapter.id = '';
        this.dialogChild = true;
      },

      // 07 删除一个章节
      deleteOne(param) {
        this.$confirm('确定删除章节 - ' + param.title + ' ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            chapter.deleteOne(param.id).then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getChapterList();
            })
          }
        )
      },

      // 08 修改
      updateOne(row) {
        this.title = "修改章节";
        this.showTitle = false;
        this.chapter = {...row};
        this.dialogChild = true;
      },

      // 18 批量导入
      importChapter() {
        this.dialogFormVisible = true
        this.uploadUrl = "http://127.0.0.1:8001/eduService/chapter/chapterImport/" + this.courseId;
      },

      // 19 视频上传
      uploadVideo(chapterId) {
        this.dialogVideo = true;
        this.chapter = {id: chapterId};
        this.video.videos = [];
      },
      handleChangeVideo(file, fileList) {
        this.video.videos = fileList.slice(-3);
      },
      uploadSuccess(response, file, fileList) {
        this.chapter.videoId = response.data.id;
        chapter.updateOne(this.chapter).then(
          this.uploadSuccessAfter()
        );
      },
      uploadSuccessAfter() {
        this.getChapterList();
        this.$message({
          type: 'success',
          message: '视频上传成功!',
        })
      },

      // 20 删除视频
      deleteVideo(id) {
        this.$confirm('确定删除视频 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            chapter.deleteVideo(id).then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getChapterList();
            })
          }
        )
      },

      // 19 课程章节批量导入成功提示
      uploadChapterSuccess() {
        this.$message({
          type: 'success',
          message: '批量导入成功',
        });
      },

      // 04 保存课程基础信息
      saveCourse() {
        var data = this.form;
        if (!(data.title) || !(data.teacherId) || !(data.subjectIds) || !(data.cover)) {
          this.$message({
            type: 'warning',
            message: '请填写数据后重试',
          });
          return;
        }
        if (this.courseId != -1) {
          data.subjectId = data.subjectIds[1];
          data.subjectParentId = data.subjectIds[0];
          course.updateOne(this.form).then(response => {
            this.courseId = response.data.courseId;
            this.pname = this.form.title;
            this.active = 2;
            this.loading = true;
            this.getChapterList();
            setInterval(() => {
              this.loading = false;
              clearInterval();
            }, 400)
            this.dialogBaseInfo = false;
            this.getList();
          })
        } else {
          data.subjectId = data.subjectIds[1];
          data.subjectParentId = data.subjectIds[0];
          course.saveOne(this.form).then(response => {
            this.courseId = response.data.courseId;
            this.form.id = response.data.courseId;
            this.pname = this.form.title;
            this.active = 2;
            this.loading = true;
            setInterval(() => {
              this.loading = false;
              clearInterval();
            }, 400)
          });
          this.dialogBaseInfo = false;
          this.getList();
        }
      },

      // 01 上传视频封面图片
      handleAvatarSuccess(res, file) {
        this.conver = res.data.url
        this.form.cover = this.conver
        console.log(this.form)
      },
      beforeAvatarUpload(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error('上传封面图片大小不能超过 10MB!');
        }
        return isLt10M;
      },

      // 点击修改课程基础信息按钮
      alterBaseInfo(id) {
        this.dialogBaseInfo = true;
        this.getInfoById(id);
        this.getSubjectList();
        this.getTeacherList();
      },

      // 02 获取讲师列表
      getTeacherList() {
        teacher.getAll().then(response => {
          this.teachers = response.data.items;
        })
      },

      // 03 获取课程分类列表
      getSubjectList() {
        subject.getAll().then(response => {
          this.options = response.data.list;
        })
      },

      getInfoById(id) {
        course.getInfoById(id).then(response => {
          this.form = response.data.form;
          this.conver = response.data.form.cover;
        })
      }


    },
    mounted() {
    }, watch: {
      dialogFormVisible(newVal, oldVal) {
        if (oldVal) {
          this.getChapterList()
        }
      },
      dialogVideo(newVal, oldVal) {
        if (oldVal) {
          this.getChapterList()
        }
      }
    }
  };
</script>
